<template>
  <el-dialog width="600px" :title="type === 'add' ? '新增部门' : '编辑部门'" :visible="visible" @close="onCloseDialog">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="110px" label-position="left" style="padding-right: 10px;">
      <el-form-item label="部门名称：" prop="name">
        <el-input v-model="formData.name" placeholder="2-10个字符" />
      </el-form-item>
      <el-form-item label="部门编码：" prop="code">
        <el-input v-model="formData.code" placeholder="2-10个字符" />
      </el-form-item>
      <el-form-item label="部门负责人：" prop="managerId">
        <el-select v-model="formData.managerId" placeholder="请选择负责人" style="width: 100%;">
          <el-option v-for="item in managerList" :key="item.id" :value="item.id" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍：" prop="introduce">
        <el-input v-model="formData.introduce" placeholder="1-100个字符" type="textarea" :rows="4" />
      </el-form-item>
      <el-form-item>
        <el-row>
          <el-col :span="12" :offset="5">
            <el-button type="primary" style="margin-right: 40px;" @click="onConfirmOperate">确定</el-button>
            <el-button @click="onCloseDialog">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { getManagerListAPI, addDepartmentAPI, getDepartmentDetailAPI, updateDepartmentAPI } from '@/api/department'

const emptyFormData = {
  name: '', // 部门名称
  code: '', // 部门编码
  managerId: '', // 部门负责人id
  introduce: '' // 部门介绍
}

export default {
  props: {
    // 所有的部门列表
    departments: {
      type: Array,
      default: () => [],
      required: true
    }
  },
  data() {
    return {
      visible: false, // 是否显示弹窗
      operatedDepartmentId: 0, // 被操作的部门id
      type: '', // 新增还是编辑
      // 表单数据
      formData: { ...emptyFormData },
      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度必须为 2 到 10 个字符', trigger: 'blur' },
          {
            validator: (rules, value, callback) => {
              let departments = this.departments
              if (this.type === 'edit') {
                // 编辑部门时，部门名称不能与除自己之外的部门名称重复
                departments = departments.filter(item => item.id !== this.operatedDepartmentId)
              }
              if (departments.some(item => item.name === value)) {
                callback(new Error('该部门名称已存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '长度必须为 2 到 10 个字符', trigger: 'blur' },
          {
            validator: (rules, value, callback) => {
              let departments = this.departments
              if (this.type === 'edit') {
                // 编辑部门时，部门编码不能与除自己之外的部门编码重复
                departments = departments.filter(item => item.id !== this.operatedDepartmentId)
              }
              if (departments.some(item => item.code === value)) {
                callback(new Error('该部门编码已存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        managerId: [
          { required: true, message: '请选择部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 100, message: '长度必须为 1 到 100 个字符', trigger: 'blur' }
        ]
      },
      managerList: [] // 部门负责人列表
    }
  },
  created() {
    // 获取部门负责人列表
    this.getManagerList()
  },
  methods: {
    // 打开弹窗
    async open(type, id) {
      // 打开弹窗
      this.visible = true
      this.operatedDepartmentId = id
      this.type = type
      if (type === 'add') {
        // 打开新增部门
        // 新增部门时表单数据为空
        this.formData = { ...emptyFormData }
      } else {
        // 打开编辑部门
        // 获取部门详情
        this.formData = await getDepartmentDetailAPI(id)
      }
    },
    // 重置表单，关闭弹窗
    onCloseDialog() {
      this.$refs.formRef.resetFields()
      this.visible = false
    },
    // 获取部门负责人列表
    async getManagerList() {
      this.managerList = await getManagerListAPI()
    },
    // 确定操作
    onConfirmOperate() {
      // 校验表单
      this.$refs.formRef.validate(async(isOk) => {
        if (isOk) {
          if (this.type === 'add') {
            // 发送新增部门请求
            await addDepartmentAPI({
              ...this.formData,
              pid: this.operatedDepartmentId
            })
          } else {
            // 发送编辑部门请求
            await updateDepartmentAPI(this.formData)
          }
          // 提示操作成功
          this.$message.success(`${this.type === 'add' ? '新增' : '编辑'}部门成功`)
          // 发送消息给父组件，以刷新组织架构列表
          this.$emit('updateDepartments')
          // 重置表单，关闭弹窗
          this.onCloseDialog()
        }
      })
    }
  }
}
</script>

<style>

</style>
